package com.base.mybaseproject.demo.Map;

import java.io.File;
import java.io.FileInputStream;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

import com.base.mybaseproject.demo.Map.MusicService.MusicBind;
import com.example.mybaseproject.R;
import com.qozix.mapview.MapView;
import com.qozix.mapview.tiles.MapTileDecoder;
import com.support.Utils;

public class MapViewActivity extends Activity implements MapTileDecoder {

	private MapView mapView;
	private MapCallOut callOut;
	private Intent musicServiceIntent;
	private MusicService musicService;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		// required...
		super.onCreate(savedInstanceState);

		// there's just the single constructor
		mapView = new MapView(this);
		// i'll set it as the content view but this isn't necessary - it's just
		// a View like any other
		setContentView(mapView);
		mapView.setDecoder(this);

		musicServiceIntent = new Intent(this, MusicService.class);
		// add some zoom levels - these all share the same downsample but that's
		// not required
		// i've added them in order of smallest to largest, but the order of
		// insertion is irrelevant
		// zoom levels are managed by a tree set, so are naturally ordered by
		// area (width * height)

		String mapPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "Travel"
				+ File.separator + "map" + File.separator;
		mapView.addZoomLevel(942, 1000, mapPath + "fragment/125_%col%_%row%.png", mapPath + "main/map.png");
		mapView.addZoomLevel(1884, 2000, mapPath + "fragment/250_%col%_%row%.png", mapPath + "main/map.png");
		mapView.addZoomLevel(3768, 4000, mapPath + "fragment/500_%col%_%row%.png", mapPath + "main/map.png");
		// mapView.addZoomLevel(9269, 7606, "tiles/1000_%col%_%row%.png",
		// "downsamples/map.png");

		// let's intercept touch events so that markers and callout don't
		// interrupt our gestures
		mapView.setShouldIntercept(true);

		// let's disallow caching explicitly - this isn't terribly helpful
		// unless dealing with especially large
		// or difficult to decode (e.g., remote) bitmaps
		mapView.setCacheEnabled(false);

		// provide the corner coordinates for relative positioning
		// mapView.registerGeolocator(42.379676, -71.094919, 42.346550,
		// -71.040280);

		// draw some of the points
		// mapView.drawPath(points.subList(0, 12));

		// set the scale after adding markers - could be set before as well
		mapView.setScale(0.5);
		addMarkView(1800, 2000);
		addMarkView(800, 200);

	}

	// when a marker is clicked, show a callout
	// the callout can be any view, and can have it's own event listeners
	private View.OnClickListener markerClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			// Utils.showToast(MapViewActivity.this, v.getTag() + "");
			// we saved the coordinate in the marker's tag
			double[] point = (double[]) v.getTag();
			// lets center the screen to that coordinate
			mapView.slideToAndCenter(point[0], point[1]);

			if (v.getTag(R.id.map_call_out) != null) {
				callOut = (MapCallOut) v.getTag(R.id.map_call_out);
				if (callOut.isShown()) {
					mapView.removeCallout(callOut);
				} else {
					mapView.addCallout(callOut, point[0], point[1], -0.5f, -1.0f, true);
					callOut.transitionIn();
				}
			} else {
				callOut = new MapCallOut(v.getContext());
				mapView.addCallout(callOut, point[0], point[1], -0.5f, -1.0f, true);
				callOut.transitionIn();
				v.setTag(R.id.map_call_out, callOut);
			}
			callOut.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					bindService(musicServiceIntent, conn, Context.BIND_AUTO_CREATE);
				}
			});

		}
	};

	// on pause let's clear the tiles bitmap data
	@Override
	public void onPause() {
		super.onPause();
		mapView.clear();
	}

	// on resume, get a new render
	@Override
	public void onResume() {
		super.onResume();
		mapView.setZoom(0);
		mapView.requestRender();
		// mapView.moveToAndCenter(1800, 2000, true);
		mapView.slideToAndCenter(1800, 2000);
	}

	// on destroy, clear and recycle bitmap data, and set all references to null
	@Override
	public void onDestroy() {
		super.onDestroy();
		mapView.destroy();
		mapView = null;
	}

	@Override
	public Bitmap decode(String fileName, Context arg1) {
		BitmapFactory.Options OPTIONS = new BitmapFactory.Options();

		OPTIONS.inPreferredConfig = Bitmap.Config.RGB_565;

		Bitmap bitmap = null;
		try {
			FileInputStream is = new FileInputStream(fileName);
			bitmap = BitmapFactory.decodeStream(is, null, OPTIONS);

		} catch (OutOfMemoryError e) {
			e.printStackTrace();
		} catch (Exception e) {

			bitmap = null;
		}

		return bitmap;
	}

	private void addMarkView(double x, double y) {
		ImageView marker = new ImageView(this);
		marker.setImageResource(R.drawable.demo_maps_marker_blue);
		marker.setTag(new double[] { x, y });
		marker.setClickable(true);
		marker.setOnClickListener(markerClickListener);
		// mapView.addMarker(marker, x, y, true);

		mapView.addMarkerAtZoom(marker, x, y, 1, true);
	}

	private ServiceConnection conn = new ServiceConnection() {

		/**
		 * 服务所在进程被kill或是crash时系统调用，而不是unbindService时调用
		 */
		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub

		}

		/**
		 * 服务连接时调用，若已经连接不进行调用
		 */
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			Utils.d("service-onServiceConnected", name.toString());
			musicService = ((MusicBind) service).getService();
			musicService.play(R.raw.bao_tu_quan);
		}
	};
}
